<?php

class admin_nodeModel extends Model {
    const USER = 1;
    const MARKET = 2;
    const COMPANY = 3;
    const CATEGORY = 4;
    const CONTENT =5;
    const WIKI = 6;
    const MESSAGE = 7;
    const SYSTEM = 8;

    const NODE_LIST_CACHE = 'ADMIN_NODE_LIST_CACHE';
    const NODE_ALL_LIST_CACHE = 'ADMIN_NODE_ALL_LIST_CACHE';
    
    
    public function getCacheList() {
        if($list = Cache_Memcache::getInstance()->get(self::NODE_LIST_CACHE)) {
            return $list;
        }
        $list = $this->where('is_show=1')->order(['pid asc', 'sort asc'])->getAll();
        Cache_Memcache::getInstance()->set(self::NODE_LIST_CACHE, $list);
        return $list;
    }
    
    public function getAllCacheList() {
        if($list = Cache_Memcache::getInstance()->get(self::NODE_ALL_LIST_CACHE)) {
            return $list;
        }
        $list = $this->order(['pid asc', 'sort asc'])->getAll();
        Cache_Memcache::getInstance()->set(self::NODE_ALL_LIST_CACHE, $list);
        return $list;
    }
    
    public function deleteListCache() {
        Cache_Memcache::getInstance()->delete(self::NODE_LIST_CACHE);
        Cache_Memcache::getInstance()->delete(self::NODE_ALL_LIST_CACHE);
    }
    
    public function getList() {
        return $this->getTree($this->getAllCacheList());
    }

    public function getHeaderList() {
        $list = $this->getCacheList();
        $data = [];
        foreach ($list as $row) {
            if($row['pid']==0) {
                $data[] = $row;
            }
        }
        return $data;
    }
    
    public function getMenuList() {
        $list = $this->getCacheList();
        return $this->getTree($list);
    }
    
    public function getTree($data, $parentId = 0) {

        if (!$data || !is_array($data)) {
            return array();
        }

        $childArray = $this->_getChildren($data, $parentId);
        if(!$childArray) {
            return array();
        }

        $treeArray = array();
        foreach ($childArray as $lines) {
            $treeArray[$lines['id']] = $lines;
            $treeArray[$lines['id']]['child'] = $this->getTree($data, $lines['id']);
        }

        return $treeArray;
    }
    
    protected function _getChildren($data, $id) {

        $childrenArray = array();
        foreach ($data as $value) {
            if ($value['pid'] == $id) {
                $childrenArray[] = $value;
            }
        }

        return $childrenArray;
    }
}
